package com.zking.frame.zc;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;

import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;

import com.zking.db.BaseDao;
import com.zking.utils.TableUtils;

/**
 * 会员查询面板
 * @sex ZC
 *
 */
public class MemberQuery extends JDialog{
	private static final long serialVersionUID = 1L;
	// 美化包
	{
		try {
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
			org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private JPanel pl;
	//北部
	private JPanel pl_north;
	private JButton bt_query;
	private JButton bt_update;
	private JButton bt_delete;
	private JButton bt_add;
	//中部
	private JPanel pl_center_right;
	//表格
	private DefaultTableModel tableModel_right;
	private JTable table_right;
	//南部
	private JPanel pl_south;
	
	
	//边框
	private Border border=BorderFactory.createMatteBorder(0,0,3,2,Color.gray);
	//颜色
	private Color blue=new Color(0x9FB6CD);
	//图片
	private ImageIcon img_query=new ImageIcon(MemberQuery.class.getResource("11.png"));
	private ImageIcon img_add=new ImageIcon(MemberQuery.class.getResource("22.png"));
	private ImageIcon img_update=new ImageIcon(MemberQuery.class.getResource("33.png"));
	private ImageIcon img_cancel=new ImageIcon(MemberQuery.class.getResource("44.png"));
	String[] columnNames_right= {"编号","客户名称","拼音码","城市",
            "地址","开户行","电话","邮政编码",
            "传真","Email","联系人","联系手机",
            "折扣","VIP","账号","期初应收","期初应付",
            "余额","创建时间"};
	//传递数据
	private  List<String> memberInfo=new ArrayList<String>();//表格的所有数据
	private String temp="id,name,pinYinCode,city,address,bankOfDeposit,tel,postalCode,"
			+ "fax,e_mail,contactPerson,contactTel,discount,isVIP,accountNumber,qcys,"
			+"qcyf,balance,creactTime";//对应的数据库列名
	private String insert="insert into client("+temp+") values(?,?,?,?,?,?,?,?,?,"
			                                                   +"?,?,?,?,?,?,?,?,?,?)";//插入数据
	private String temp2="id=?,name=?,pinYinCode=?,city=?,address=?,bankOfDeposit=?,tel=?,postalCode=?,"
			+ "fax=?,e_mail=?,contactPerson=?,contactTel=?,discount=?,isVIP=?,accountNumber=?,qcys=?,"
			+"qcyf=?,balance=?,creactTime=?";//对应的数据库列名
	private String update="update client set "+temp2+" where id=?";//更新语句
	/**
	 * 1.显示会员（数据顺序为表格上的显示数据）
	 */
	public int showMembers(String sql,Object ...params) {
		tableModel_right.setDataVector(null, columnNames_right);//清空原有数据
		BaseDao base=new BaseDao();
		try {
			List<Object[]> data=base.queryArrayListHandler(sql,params);
			for(int i=0;i<data.size();i++)
				tableModel_right.addRow(data.get(i));
			return  data.size();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}
	public MemberQuery(Frame owner,boolean modal) {
		super(owner, modal);
		Container c=getContentPane();
		c.setLayout(new BorderLayout());
        /*整个面板*/
		pl=new JPanel();
	    pl.setBackground(Color.WHITE);
	    pl.setLayout(new BorderLayout());
		
		/*顶部*/
		pl_north=new JPanel(new FlowLayout(FlowLayout.LEADING,10,15));
		pl_north.setBackground(blue);
		pl_north.setPreferredSize(new Dimension(0,50));
		c.add(BorderLayout.NORTH,pl_north);
		//查询标签
		JLabel lb_query=new JLabel("姓名:"); 
		lb_query.setFont(new Font("楷体",Font.BOLD,15));
		pl_north.add(lb_query);
		//1.查询输入框
		JTextField tf_query=new JTextField(10);
		tf_query.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		tf_query.setFont(new Font("宋体",Font.PLAIN,15));
		tf_query.setPreferredSize(new Dimension(0,25));
		pl_north.add(tf_query);
		  //1.1查询
		bt_query=new JButton(img_query);
        bt_query.setPreferredSize(new Dimension(90, 30));
		bt_query.setFont(new Font("楷体",Font.BOLD,15));
		bt_query.setBackground(new Color(0xF0F0F0));
		bt_query.setBorder(border);
		bt_query.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		bt_query.addActionListener(e->{
			String name=tf_query.getText();
			if(name.length()==0||"".equals(name)) {
				JOptionPane.showMessageDialog(MemberQuery.this,"请输入你要查询的人的姓名");
				return ;
			}
			//数据库查询
		    JOptionPane.showMessageDialog(MemberQuery.this,"查询成功，共"+
		      showMembers("select "+temp+" from client where name like ?","%"+name+"%")+"条数据。");
		});
		pl_north.add(bt_query);
		pl_north.add(new JLabel());
		  //修改
		bt_update=new JButton(img_update);
		bt_update.setPreferredSize(new Dimension(80, 30));
		bt_update.setFont(new Font("楷体",Font.BOLD,15));
		bt_update.setBackground(new Color(0xF0F0F0));
		bt_update.setBorder(border);
		bt_update.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		bt_update.addActionListener(e->{
			memberInfo.clear();//清空
			int selectRow;
			if((selectRow=table_right.getSelectedRow())==-1) {
				JOptionPane.showMessageDialog(MemberQuery.this,"请选中要修改的行");
				return ;
			}
			//添加加全部数据
			for(int i=0;i<columnNames_right.length;i++)
				memberInfo.add(""+tableModel_right.getValueAt(selectRow, i));
			new UpdateMember(MemberQuery.this, true, memberInfo);//弹窗，获得数据
			//点击取消或关闭
			if(memberInfo.isEmpty()) return ;
			//更换表格数据
			for(int i=0;i<columnNames_right.length;i++)
				tableModel_right.setValueAt(memberInfo.get(i),selectRow,i);
			//更换数据库数据
			BaseDao base=new BaseDao();
	    	String sql=update;
//	    	System.out.println("sql="+sql);
	    	memberInfo.add(memberInfo.get(0));
	    	try {
				base.update(sql,memberInfo.toArray());
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return ;
			}
	    	JOptionPane.showMessageDialog(MemberQuery.this,"修改成功。");
			memberInfo.clear();//清空
		});
		pl_north.add(bt_update);
		pl_north.add(new JLabel());
		   //删除
		bt_delete=new JButton(img_cancel);
		bt_delete.setPreferredSize(new Dimension(75, 30));
		bt_delete.setFont(new Font("楷体",Font.BOLD,15));
		bt_delete.setBackground(new Color(0xF0F0F0));
		bt_delete.setBorder(border);
		bt_delete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		bt_delete.addActionListener(e->{
			int selectRow;
			if((selectRow=table_right.getSelectedRow())!=-1) {
				if(JOptionPane.showConfirmDialog(MemberQuery.this,"确认要删除吗？", "提示", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
				   //更新数据库
					BaseDao base=new BaseDao();
			    	String sql="DELETE FROM CLIENT WHERE id=?";
			    	String id=tableModel_right.getValueAt(selectRow,0)+"";//客户ID
			    	try {
			    		// 删除语句
						String sql1 ="delete from arap WHERE customerID=?";//删除应付应收
						String sql2 ="delete from  wholesalecontent  WHERE wholeSaleId=?";//删除批发内容
						String sql3 ="SELECT id FROM wholesale WHERE customerId=?";//批发单id
						String sql4 ="delete from client where id=?";//删除客户
						base.update(sql1,id);//删除应付应收
						int wholesales_id=base.getCount(sql3,id);//批发ID
						base.update(sql2,wholesales_id);//删除批发内容
						base.update("delete FROM wholesale WHERE customerId=?",id);//删除批发
					    base.update(sql4,id);
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						JOptionPane.showMessageDialog(MemberQuery.this,"删除失败。");
						return ;
					}//返回影响行数
			    	tableModel_right.removeRow(selectRow);//移除
				   JOptionPane.showMessageDialog(MemberQuery.this,"删除成功。");
				}
			}else {
				JOptionPane.showMessageDialog(MemberQuery.this,"请选中所需删除的库单");
			}
		});
		pl_north.add(bt_delete);
		pl_north.add(new JLabel());
		   //增加
		bt_add=new JButton(img_add);
		bt_add.setPreferredSize(new Dimension(80, 30));
		bt_add.setFont(new Font("楷体",Font.BOLD,15));
		bt_add.setBackground(new Color(0xF0F0F0));
		bt_add.setBorder(border);
		bt_add.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		bt_add.addActionListener((e)->{
			memberInfo.clear();//清空
			for(int i=0;i<columnNames_right.length;i++)
				memberInfo.add(null);
			new UpdateMember(MemberQuery.this, true, memberInfo);//弹窗，获得数据
			//1.点击了子窗口的关闭按钮
			if(memberInfo.isEmpty()) return ;
			//2.点击了添加按钮
			tableModel_right.addRow(memberInfo.toArray());//增加
			System.out.println(memberInfo.get(1));
			//3.更换数据库数据
			BaseDao base=new BaseDao();
	    	String sql=insert;
	    	try {
				base.update(sql,memberInfo.toArray());
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return ;
			}
	    	TableUtils.moveToFinal(table_right, tableModel_right);
	    	JOptionPane.showMessageDialog(MemberQuery.this,"添加成功。");
			memberInfo.clear();//清空
		});
		pl_north.add(bt_add);
		//右边
		pl_center_right=new JPanel(new BorderLayout());
		pl_center_right.setBackground(Color.white);
		c.add(BorderLayout.CENTER,pl_center_right);
		       //表格
		tableModel_right=new DefaultTableModel(columnNames_right,0) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				// TODO Auto-generated method stub
				return false;
			}
		};
		table_right=new JTable(tableModel_right);
		JScrollPane sp_center_right=new JScrollPane(table_right);
		sp_center_right.getViewport().setOpaque(false);
		sp_center_right.setBackground(Color.WHITE);
		pl_center_right.add(BorderLayout.CENTER,sp_center_right);
		
		/*底部*/
		pl_south=new JPanel(null);
		pl_south=new JPanel(new FlowLayout(FlowLayout.CENTER,30, 10));
		pl_south.setBackground(blue);
		pl_south.setPreferredSize(new Dimension(0,60));
		c.add(BorderLayout.SOUTH,pl_south);
		
		//显示数据库里的数据
		showMembers("select "+temp+" from client");
		TableUtils.interlacedColorChange(table_right,null,null);
		setTitle("会员管理");
		setSize(1360,685);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setLocationRelativeTo(owner);
		setVisible(true);
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        new MemberQuery(null, true);
	}
}

